package com.heima.test;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.ArticleApp;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.search.entity.ApArticleDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-07-12 10:35
 */
@SpringBootTest(classes = ArticleApp.class)
@RunWith(SpringRunner.class)
@Slf4j
public class BatchImportES {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private IApArticleService apArticleService;

    private static final String indexName = "app_info_article"; //es上的名


    /**
     * 从当前文章数据库查询文章列表数据，将数据批量导入索引库
     */
    @Test
    public void testBatchImport() {
        //1.查询数据库文章列表
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        List<ApArticle> list = apArticleService.list(queryWrapper);
        //2.构建索引库文档对象
        List<ApArticleDoc> docList = list.stream().map(apArticle -> {  //集合对象.stream().map（）必须是集合--用户集合转换类型
            ApArticleDoc doc = new ApArticleDoc();
            BeanUtils.copyProperties(apArticle, doc);
            return doc;
        }).collect(Collectors.toList());

        //3.执行批量导入索引库
        BulkRequest request = new BulkRequest();
        for (ApArticleDoc doc : docList) {
            request.add(new IndexRequest(indexName).id(doc.getId().toString()).source(JSON.toJSONString(doc), XContentType.JSON));

        }
        restHighLevelClient.bulkAsync(request, RequestOptions.DEFAULT, new ActionListener() {

            @Override
            public void onResponse(Object o) {
                log.info("执行成功");
            }

            @Override
            public void onFailure(Exception e) {
                log.error("执行失败", e);
            }
        });

    }
}